import base from "@src/store/base";
import {bindMember, checkWxCardState} from "@src/api/member";
import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import router from "@src/router";
import member from "@src/store/member";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor', 'businessName'],
  },{
    store: member,
    actions: ['getBaseInfo', 'syncWxCard']
  }],
  data: {},
  methods: {
    onLoad() {
      this.fetchData();
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('oldMemberData', (data) => {
        let {ivStr, encryptedData, oldMemberInfo} = data;
        this.setData({ivStr, encryptedData, getPageData: oldMemberInfo, offlineMember: oldMemberInfo.offlineMember});
      })
    },
    fetchData() {
      checkWxCardState().then(res => {
        if (res.code === 0) {
          this.setData({wxCardState: {hasActive: res.data.hasActive, hasGet: res.data.hasGet}})
        }
      })
    },
    handleMessageBtnClick() {
      wx.showModal({
        title: "提示",
        content: "信息有误请联系商家",
        showCancel: false
      });
    },
    handleBindMember() {
      wx.showLoading({title: "绑定中...", mask: true});
      let data = {
        encryptedData: this.data.encryptedData,
        ivStr: this.data.ivStr
      };
      bindMember(data).then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          // 刷新会员数据
          this.getBaseInfo();
          if (this.data.wxCardState.hasGet) {
            wx.showModal({
              title: "提示",
              content: `会员导入成功`,
              showCancel: false,
              confirmText: "去首页",
              success: sm => {
                if (sm.confirm) {
                  router.push({name: "index"})
                }
              }
            });
          } else {
            console.info("sync Card")
            this.syncWxCard();
          }
        } else {
          console.info("bindMember error", res)
          wx.showToast({
            title: res.msg, icon: "none", duration: 3000
          });
        }
      }).catch((error) => {
        wx.hideLoading();
        console.error("bindMember", error)
      })
    }
  }
})
